import { t } from 'i18next'
import React, { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'
import { StyledWrap } from './style'
import StyleChooseSelect from './StyleChooseSelect'
import SinglePollModal, { SinglePollData } from '@/components/SinglePollModal'
import { useSinglePollStore } from '@/components/SinglePollModal/store'
import { StyledView } from './style'
import { initData, StyleData, vmpStyleData } from './interface'
import { DragDropContextProvider } from '@/plugins/dnd'
import { Modal } from '@kedacom/react-next'
import Alert from '@/components/Alert'
import { Poll, VmpMember } from '../interface'
import { useSize } from '@kedacom/hooks'
import { MemberItem } from './item'
import { useTableAllStore } from '../../main/table/all/store'
import shallow from 'zustand/shallow'
import { Mt } from '@/api/manager/mt'
import { Meeting } from '@/api/manager/meeting'
import { useVmpTypeStore } from '../store.get'
import { IMcc } from '@/api/manager/type'

type ScrollBarProps = {
	/** 是否显示样式选择滚动条 */
	isShowScrollBar?: boolean
	/** 是否只显示一个样式 */
	isShowSingle?: boolean
	/** 样式是否可选择 */
	isBarDisabled?: boolean
	/** 画面合成样式滑轮显示个数 */
	scrollLength?: number
	/** 样式选择事件 */
	onSelect?: (val: number, prev: number) => void
}
type BoxProps = {
	/** 是否显示样式选择框 */
	isShowBox?: boolean
	/** 样式选择框是否可操作 */
	isBoxDisabled?: boolean
	/** 选择框设置项显示隐藏 */
	/** 只可从外部拖入，不可相互拖拽 */
	onlyDragIn?: boolean
	/** 是否显示加号图标 */
	noAddIcon?: boolean
	/** 样式框修改 */
	onBoxChange?: () => void
}
export type VmpViewProps = {
	layout: number
	members: VmpMember[]
	disabled?: boolean
	mode?: number
} & ScrollBarProps &
	BoxProps
const getStyleData = (style: number) => vmpStyleData.find((item) => item.id === style) ?? vmpStyleData[0]
function getScale(width: number | null, height: number | null) {
	let rate = 1
	const _rate = 0.576
	const _width = 520
	const _height = 300
	if (height != null && width != null) {
		if (height > width * _rate) {
			/**高度太高 */
			/**计算新比列和宽度有关*/
			rate = width / _width
		} else {
			/**宽度太宽 */
			/**计算新比列和宽度有关 */
			rate = height / _height
		}
	}
	return rate
}
function VmpView(props: VmpViewProps, ref: any) {
	const {
		layout: orgStyle,
		members,
		disabled = false,
		isShowScrollBar = true,
		isShowSingle = false,
		isBarDisabled = false,
		onSelect,
		isBoxDisabled = false,
		onlyDragIn = false,
		noAddIcon = false,
		onBoxChange,
		mode,
	} = props
	/**计算缩放比列 */
	const [scale, setScale] = useState<number>(1)
	const refContainer = useRef<HTMLDivElement>(null)
	const scaleSetTimeout = useRef<NodeJS.Timeout>()
	const { width = 0, height = 0 } = useSize(refContainer)
	useLayoutEffect(() => {
		clearTimeout(scaleSetTimeout.current)
		let rate = getScale(0, 0)
		setScale(rate)
		scaleSetTimeout.current = setTimeout(() => {
			let rate = getScale(width, height)
			setScale(rate)
		}, 100)
		return () => {
			clearTimeout(scaleSetTimeout.current)
		}
	}, [width, height])
	const { tableAll, getMtModel } = useTableAllStore(
		(state) => ({ tableAll: state.tree, getMtModel: state.getMtModel }),
		shallow
	)
	const [styleData, setStyleData] = useState(vmpStyleData[0]) //当前样式数据
	const [memberList, setMemberList] = useState<VmpMember[]>([])
	const [curPollData, setCurPollData] = useState<SinglePollData>({ index: 0, poll: null })
	const [open, setOpen] = useState(false)
	useEffect(() => {
		// if (_isStart && _isEdit) return
		let curStyleData = getStyleData(orgStyle)
		let data: VmpMember[] = new Array(curStyleData.listItemCount).fill({}).map((_, index) => {
			let x = members.find((item) => item.chn_idx === getChnidx(index, curStyleData)) ?? initData
			return {
				...x,
				//todo 计算属性不能解构，后面版本修改
				name: x.name,
			}
		})
		let mtKeys = data.map((x) => x.mt_key)
		let result = getMtModel(mtKeys)
		for (let i = 0; i < data.length; i++) {
			const item = data[i]
			if (item && item.mt_key /**存在查询节点的mt_key */) {
				const _item = result[i]
				if (_item /**查询当前终端详情 */) {
					item.online = _item.mcc.status.isOnline ? 1 : 0
					item.mute = _item.mcc.status.isMute ? 1 : 0
					item.video_src = _item.mcc.isMt && _item.mcc.status.isVideoSrc ? 1 : 0
				} else {
					/**在呼起状态直接删除终端*/
					item.online = 0
				}
			}
		}
		setStyleData(curStyleData)
		setMemberList(data)
	}, [orgStyle, members])
	/**在离线等状态更新*/
	useEffect(() => {
		setMemberList((preState) => {
			let mtKeys = preState.map((x) => x.mt_key)
			let result = getMtModel(mtKeys)
			return preState.map((item, i) => {
				if (item && item.mt_key /**存在查询节点的mt_key */) {
					const _item = result[i]
					if (_item /**查询当前终端详情 */) {
						item.online = _item.mcc.status.isOnline ? 1 : 0
						item.mute = _item.mcc.status.isMute ? 1 : 0
						item.video_src = _item.mcc.isMt && _item.mcc.status.isVideoSrc ? 1 : 0
					} else {
						/**在呼起状态直接删除终端*/
						item.online = 0
					}
				}
				return item
			})
		})
	}, [tableAll])
	const vmpStyleSelect = (id: number) => {
		// if (id === styleData.id) return
		onSelect?.(id, styleData.id)
		let curStyleData = getStyleData(id)
		let data = new Array(curStyleData.listItemCount).fill({}).map((_, index) => {
			let x: VmpMember = memberList.find(
				(item) => item.chn_idx === getChnidx(index, curStyleData) && item.member_type !== 0
			) ?? { ...initData }
			return {
				...x,
				name: x.name,
			}
		})
		setStyleData(curStyleData)
		setMemberList(data)
	}
	const getChnidx = (index: number, data?: StyleData) => {
		let obj = data ?? styleData
		return obj.order ? obj.order[index] - 1 : index
	}
	const handleDrop = (dataTransfer: any, index: number) => {
		if (mode === 4) {
			return
		}
		let dragFromListName = dataTransfer.from
		let _sourceData = dataTransfer.data
		let sourceData: IMcc
		let newArr = [...memberList]
		if (dragFromListName === 'userItem') {
			if (_sourceData.isMt) {
				//从用户列表拖拽
				sourceData = new Mt(_sourceData)
				newArr[index] = {
					mt_id: sourceData.mtid,
					mt_key: sourceData.mtKey,
					account: sourceData.account,
					account_type: sourceData.accountType,
					INITIAL_NAME: sourceData.INITIAL_NAME,
					name: sourceData.name,
					portrait: sourceData.portrait,
					conf_e164: sourceData.confE164,
					online: sourceData.status.isOnline ? 1 : 0,
					mute: sourceData.status.isMute ? 1 : 0,
					chn_idx: getChnidx(index),
					member_type: 1,
					video_src: sourceData.status.isVideoSrc ? 1 : 0,
				}
			} else {
				sourceData = new Meeting(_sourceData)
				newArr[index] = {
					mt_id: sourceData.smcuMtid,
					mt_key: sourceData.mtKey,
					account: sourceData.account,
					account_type: 5,
					INITIAL_NAME: sourceData.name,
					name: sourceData.name,
					portrait: '',
					conf_e164: '',
					online: sourceData.status.isOnline ? 1 : 0,
					mute: sourceData.status.isMute ? 1 : 0,
					chn_idx: getChnidx(index),
					member_type: 1,
					video_src: 0,
				}
			}
		} else if (dragFromListName === 'vmpItem' && !onlyDragIn) {
			//在风格内部相互拖拽
			let sourceIndex = dataTransfer.index
			if (newArr[index].member_type === 6) return
			if (newArr[index].member_type !== 0) {
				//todo name计算属性，后面版本修复
				let temp = { ...newArr[index], name: newArr[index].name, chn_idx: getChnidx(sourceIndex) }
				newArr[index] = { ...newArr[sourceIndex], name: newArr[sourceIndex].name, chn_idx: getChnidx(index) }
				newArr[sourceIndex] = temp
			} else {
				//todo name计算属性，后面版本修复
				newArr[index] = { ...newArr[sourceIndex], name: newArr[sourceIndex].name, chn_idx: getChnidx(index) }
				newArr[sourceIndex] = { ...initData }
			}
		}
		setMemberList(newArr)
		onBoxChange?.()
	}
	const onTypeSelect = (index: number, name: string, type: number, member: VmpMember) => {
		if (type === 6) {
			setCurPollData({
				index: index,
				poll: member.poll ?? null,
			})
			setOpen(true)
			return
		}
		if (type === 2 || type === 3 || type === 4 || type === 7) {
			if (memberList.find((item) => item.member_type === type)) {
				Alert(t('在其他通道已经设置了{{name}}', { name: name }))
				return
			}
		}
		var newList = [...memberList]
		newList[index] = {
			name: '',
			chn_idx: getChnidx(index),
			member_type: type,
		}
		setMemberList(newList)
		onBoxChange?.()
	}
	const onType6Select = (index: number, poll?: Poll) => {
		var newList = [...memberList]
		newList[index] = {
			name: '',
			chn_idx: getChnidx(index),
			member_type: 6,
			poll,
		}
		setMemberList(newList)
		onBoxChange?.()
	}
	const clearVmpMember = (index: number) => {
		let newArr = [...memberList]
		newArr[index] = { ...initData }
		setMemberList(newArr)
		onBoxChange?.()
	}
	//获取总轮询人数
	const getPollMembersNum = () => {
		let count = 0
		memberList.forEach((member) => {
			if (member.member_type === 6 && member.poll && member.poll.members.length !== 0) {
				count += member.poll.members.length
			}
		})
		return count
	}
	useEffect(() => {
		const useStore = useVmpTypeStore.getState().getStore()
		useStore.setState(() => ({ memberList: memberList }))
	}, [memberList])
	useImperativeHandle(ref, () => ({
		getValue() {
			return memberList.filter((i) => !(!i.account && i.member_type === 0))
		},
		getStyle() {
			return styleData.id
		},
	}))
	return (
		<StyledWrap className="vmp-select-box">
			{isShowScrollBar && (
				<StyleChooseSelect
					styleData={styleData}
					onSelect={vmpStyleSelect}
					isShowSingle={isShowSingle}
					disabled={disabled || isBarDisabled}
				/>
			)}
			<DragDropContextProvider>
				<StyledView disabled={isBoxDisabled} ref={refContainer} scale={scale} className="style-container">
					<div
						className={`vmp-list ${styleData.className} ${scale === 0 ? 'scale0' : ''}`}
						data-key={styleData.dataKey}
					>
						{memberList.map((member, index) => {
							return (
								<MemberItem
									key={`${index}$${member.member_type}$${member.mt_key}`}
									index={index}
									dataKey={styleData.order ? styleData.order[index] : index + 1}
									member={member}
									noAddIcon={noAddIcon}
									disabled={isBoxDisabled || disabled}
									onTypeSelect={onTypeSelect}
									onDrop={handleDrop}
									onClearVmpMember={clearVmpMember}
								/>
							)
						})}
					</div>
				</StyledView>
			</DragDropContextProvider>
			<Modal
				open={open}
				title={t('单通道轮询')}
				needFooter={false}
				width={850}
				height={612}
				onCancel={() => {
					setOpen(false)
					useSinglePollStore.getState().reset()
				}}
			>
				<SinglePollModal
					setOpen={setOpen}
					data={curPollData}
					okCallBack={(data: SinglePollData) => {
						onType6Select(data.index, data.poll ?? undefined)
					}}
					getPollMembersNum={getPollMembersNum}
				/>
			</Modal>
		</StyledWrap>
	)
}
export default forwardRef(VmpView) as (props: VmpViewProps & { ref?: any }) => React.ReactElement
